
package com.platform.modules.mall.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.platform.common.utils.Constant;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.dao.MallOrderGoodsDao;
import com.platform.modules.mall.dao.MallTemplateDao;
import com.platform.modules.mall.dao.MallUserDao;
import com.platform.modules.mall.entity.MallOrderEntity;
import com.platform.modules.mall.entity.MallOrderGoodsEntity;
import com.platform.modules.mall.entity.MallTemplateEntity;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.service.WxSendMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 一次性订阅消息Service实现类
 *
 * @author
 * @date 2019-07-04 18:08:15
 */
@Slf4j
@Service("wxSendMsgService")
public class WxSendMsgServiceImpl implements WxSendMsgService {
    @Autowired
    private WxMaMsgService maMsgService;
    @Autowired
    private MallTemplateDao templateDao;
    @Autowired
    private MallUserDao userDao;
    @Autowired
    private MallOrderGoodsDao orderGoodsDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean notifyPaySuccess(MallOrderEntity orderInfo, String templateCode) {
        log.info("----------微信消息通知----------");
        log.info("订单编号：" + orderInfo.getOrderSn() + "；templateCode：" + templateCode);
        WxMaSubscribeMessage paras = new WxMaSubscribeMessage();

        MallTemplateEntity templateVo = templateDao.selectOne(new QueryWrapper<MallTemplateEntity>().eq("TEMPLATE_CODE", templateCode));
        if (null == templateVo) {
            return false;
        }
        MallUserEntity userVo = userDao.selectById(orderInfo.getUserId());
        String page = "/pages/ucenter/orderDetail/orderDetail?id=";
        if (orderInfo.getOrderType() == 3) {
            page = "/pages/ucenter/skillDetail/skillDetail?id=";
        }
        paras.setTemplateId(templateVo.getTemplateId());
        paras.setToUser(userVo.getOpenId());
        paras.setPage(page + orderInfo.getId());

        //订单的商品
        Map<String, Object> orderGoodsParam = new HashMap<>(2);
        orderGoodsParam.put("orderId", orderInfo.getId());
        List<MallOrderGoodsEntity> orderGoods = orderGoodsDao.queryAll(orderGoodsParam);
        StringBuilder body = new StringBuilder();
        if (null != orderGoods) {
            for (MallOrderGoodsEntity goodsVo : orderGoods) {
                if (body.length() < 100) {
                    body.append(goodsVo.getGoodsName()).append("*").append(goodsVo.getNumber()).append("、");
                }
            }
            if (body.length() > 0) {
                body = new StringBuilder(body.substring(0, body.length() - 1));
            }
        }
        //-------------------- 根据templateType使用不同的模板 --------------------
        //新订单提醒
        if (templateCode.equals(Constant.STR_ZERO)) {
            paras.setData(Lists.newArrayList(
                    new WxMaSubscribeMessage.MsgData("character_string4", orderInfo.getOrderSn()),
                    new WxMaSubscribeMessage.MsgData("date6", DateUtils.format(orderInfo.getAddTime(), DateUtils.DATE_TIME_PATTERN)),
                    new WxMaSubscribeMessage.MsgData("thing2", body.toString()),
                    new WxMaSubscribeMessage.MsgData("amount3", orderInfo.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString() + "元"),
                    new WxMaSubscribeMessage.MsgData("thing1", transOrderType(orderInfo.getOrderType()))
            ));
        }
        //下单成功通知
        if (templateCode.equals(Constant.ONE)) {
            paras.setData(Lists.newArrayList(
                    new WxMaSubscribeMessage.MsgData("character_string6", orderInfo.getOrderSn()),
                    new WxMaSubscribeMessage.MsgData("date4", DateUtils.format(orderInfo.getAddTime(), DateUtils.DATE_TIME_PATTERN)),
                    new WxMaSubscribeMessage.MsgData("thing2", body.toString()),
                    new WxMaSubscribeMessage.MsgData("amount3", orderInfo.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString() + "元"),
                    new WxMaSubscribeMessage.MsgData("thing1", transOrderType(orderInfo.getOrderType()))
            ));
        }
        //订单评价提醒
        if (templateCode.equals(Constant.TWO)) {
            paras.setData(Lists.newArrayList(
                    new WxMaSubscribeMessage.MsgData("character_string1", orderInfo.getOrderSn()),
                    new WxMaSubscribeMessage.MsgData("time2", DateUtils.format(orderInfo.getAddTime(), DateUtils.DATE_TIME_PATTERN)),
                    new WxMaSubscribeMessage.MsgData("thing3", body.toString()),
                    new WxMaSubscribeMessage.MsgData("amount4", orderInfo.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString() + "元"),
                    new WxMaSubscribeMessage.MsgData("thing5", transOrderType(orderInfo.getOrderType()))
            ));
        }
        //退款
        if (templateCode.equals(Constant.STR_THREE)) {
            paras.setData(Lists.newArrayList(
                    new WxMaSubscribeMessage.MsgData("character_string4", orderInfo.getOrderSn()),
                    new WxMaSubscribeMessage.MsgData("date3", DateUtils.format(orderInfo.getAddTime(), DateUtils.DATE_TIME_PATTERN)),
                    new WxMaSubscribeMessage.MsgData("thing1", body.toString()),
                    new WxMaSubscribeMessage.MsgData("amount2", orderInfo.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString() + "元"),
                    new WxMaSubscribeMessage.MsgData("thing8", transOrderType(orderInfo.getOrderType()))
            ));
        }
        //秒杀成功通知
        if (templateCode.equals(Constant.STR_FOUR)) {
            paras.setData(Lists.newArrayList(
                    new WxMaSubscribeMessage.MsgData("character_string1", orderInfo.getOrderSn()),
                    new WxMaSubscribeMessage.MsgData("time2", DateUtils.format(orderInfo.getAddTime(), DateUtils.DATE_TIME_PATTERN)),
                    new WxMaSubscribeMessage.MsgData("thing3", body.toString()),
                    new WxMaSubscribeMessage.MsgData("thing4", transOrderType(orderInfo.getOrderType()))
            ));
        }
        //订单配送通知
        if (templateCode.equals(Constant.STR_FIVE)) {
            paras.setData(Lists.newArrayList(
                    new WxMaSubscribeMessage.MsgData("character_string1", orderInfo.getOrderSn()),
                    new WxMaSubscribeMessage.MsgData("date3", DateUtils.format(orderInfo.getAddTime(), DateUtils.DATE_TIME_PATTERN)),
                    new WxMaSubscribeMessage.MsgData("thing8", body.toString()),
                    new WxMaSubscribeMessage.MsgData("name6", orderInfo.getShippingName()),
                    new WxMaSubscribeMessage.MsgData("character_string7", orderInfo.getShippingNo())
            ));
        }
        try {
            maMsgService.sendSubscribeMsg(paras);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public boolean sendUniformMsg(MallOrderEntity orderInfo, String templateCode, String openid) {
        log.info("---------- 小程序消息通知----------");
        log.info("用户openid" + openid + "；templateCode：" + templateCode);

        try {
            WxMaUniformMessage tem = new WxMaUniformMessage();
            MallTemplateEntity templateVo = templateDao.selectOne(new QueryWrapper<MallTemplateEntity>().eq("TEMPLATE_CODE", templateCode));
            if (null == templateVo) {
                return false;
            }
            // 发送的是公众号模版
            tem.setMpTemplateMsg(true);
            tem.setTemplateId(templateVo.getTemplateId());
            tem.setToUser(openid);
            // 公众号发送通知填写公众号appid
            tem.setAppid("wx88eeb5974069fb64");

            List<WxMaTemplateData> data;
            data = new ArrayList<>();

            List<MallOrderGoodsEntity> orderGoods = orderInfo.getOrderGoodsEntityList();
            StringBuilder body = new StringBuilder();
            if (null != orderGoods) {
                for (MallOrderGoodsEntity goodsVo : orderGoods) {
                    if (body.length() < 100) {
                        body.append(goodsVo.getGoodsName()).append("*").append(goodsVo.getNumber()).append("、");
                    }
                }
                if (body.length() > 0) {
                    body = new StringBuilder(body.substring(0, body.length() - 1));
                }
            }
            switch (templateCode) {
                case Constant.STR_SIX:
                    if (StringUtils.isNotBlank(templateVo.getTemplateData())) {
                        // {"first":"%s","keyword1":"%s","keyword2":"%s","keyword3":"%s","keyword4":"%s","keyword5":"%s","remark":"%s"}
                        templateVo.setTemplateData(String.format(templateVo.getTemplateData(), "您有一笔新的农商积分兑换订单",
                                orderInfo.getId(), body, orderInfo.getConsignee(), orderInfo.getMobile(), orderInfo.getAddress(), "请登录PC后台及时处理"));
                        JSONObject js = (JSONObject) JSONObject.parse(templateVo.getTemplateData());
                        List list = Arrays.asList(js.keySet().stream().toArray());
                        for (Object str : list) {
                            data.add(new WxMaTemplateData(String.valueOf(str), js.getString(String.valueOf(str))));
                        }
                    }
                    break;
                default:
                    break;
            }
            tem.setData(data);
            maMsgService.sendUniformMsg(tem);
        } catch (Exception e) {
            log.error("推送报错", e);
        }
        return true;
    }


    public static void main(String[] args) {
        MallTemplateEntity templateVo = new MallTemplateEntity();
        String str = "{\"first\":\"%s\",\"keyword1\":\"%s\",\"keyword2\":\"%s\",\"keyword3\":\"%s\",\"keyword4\":\"%s\",\"keyword5\":\"%s\",\"remark\":\"%s\"}";
        templateVo.setTemplateData(str);
        templateVo.setTemplateData(String.format(templateVo.getTemplateData(), 1, 2, 3, 4, 5, 6, 7));
        System.out.println(templateVo.getTemplateData());
    }


    private String transOrderType(int type) {
        switch (type) {
            case 1:
                return "商城订单";
            case 2:
                return "店铺自提订单";
            case 3:
                return "秒杀订单";
            case 4:
                return "积分订单";
            default:
                return "商城订单";
        }
    }


}
